import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy as np

# 数据
methods = ['Hybrid', 'IBVS', 'PBVS']
final_error_mean = np.array([19.8, 48.8, 31.7])
final_error_std = np.array([3.0, 7.3, 4.8])
T_conv_mean = np.array([2.0, 2.2, 1.7])
T_conv_std = np.array([0.3, 0.3, 0.3])
success_rate = np.array([100.0, 81.3, 88.9])
x = np.arange(len(methods))

# 创建三轴图
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis['right'] = new_fixed_axis(loc='right', axes=par2, offset=(offset, 0))
par2.axis['right'].toggle(all=True)

# 左轴：终误差柱状图
bar_width = 0.5
bars = host.bar(x, final_error_mean, bar_width, color='lightblue',
                label='Final error (mm)', yerr=final_error_std, capsize=4)

# 右轴1：收敛时间
(line1,) = par1.plot(x, T_conv_mean, 's--', color='orange', label='T_conv (s)')
par1.errorbar(x, T_conv_mean, yerr=T_conv_std, fmt='s--', color='orange', capsize=3)

# 右轴2：成功率
(line2,) = par2.plot(x, success_rate, 'o-', color='red', label='Success rate (%)')

# 坐标轴与标签
host.set_xlabel('Method')
host.set_ylabel('Final error (mm)')
par1.set_ylabel('T_conv (s)')
par2.set_ylabel('Success rate (%)')

host.set_xticks(x)
host.set_xticklabels(methods)

# 颜色与范围
host.set_ylim(0, 60)
par1.set_ylim(0, 3)
par2.set_ylim(0, 110)

# 图例
lines = [bars, line1, line2]
host.legend(lines, [l.get_label() for l in lines],loc='upper left', bbox_to_anchor=(0.52, 1))

host.grid(True, linestyle='--', alpha=0.5)
host.set_title('Hybrid vs IBVS vs PBVS Performance Summary')

plt.savefig('output_final.png', dpi=300, bbox_inches='tight')
plt.show()
